import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:aliface/aliface.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final inputController = TextEditingController();
  InitSdkData? _initSdkData;
  VerifierData? _verifierData;
  String? _metaInfo;

  @override
  void initState() {
    super.initState();
    initAlifaceState();
  }

  Future<void> initAlifaceState() async {
    InitSdkData? initSdkData;
    try {
      final result = await Aliface.registerFace;
      initSdkData = result;
    } on PlatformException {
      initSdkData?.code = false;
      initSdkData?.msg = "PlatformException";
    }
    final metaInfo = await Aliface.getMetaInfo;
    if (kDebugMode) {
      print(metaInfo);
    }
    setState(() {
      _metaInfo = metaInfo;
    });
    if (!mounted) return;
    setState(() {
      _initSdkData = initSdkData;
    });
  }

  void initStartVerifier() async {
    final result =
        await Aliface.startVerifier(certifyId: inputController.value.text);
    setState(() {
      _verifierData = result;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: [
              TextField(
                controller: inputController,
              ),
              Text("Aliface init state:${_initSdkData?.toJson()}"),
              Text(
                  "Aliface verifier result:${_verifierData?.msg}===>${_verifierData?.code}"),
              Text("Aliface metaInfo result:$_metaInfo"),
              TextButton(
                  onPressed: () {
                    initStartVerifier();
                  },
                  child: _verifierData == null
                      ? const Text("开始认证")
                      : Text("认证结果：${_verifierData?.toJson()}"))
            ],
          ),
        ),
      ),
    );
  }
}
